import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../../service/translation_service.dart';
import '../../others/manager/package_info_manager.dart';

///
/// 图形验证码
///
class VerifyCaptchaView extends StatelessWidget {
  final String url;
  final RxDouble webviewHeight;

  final Function(String?, String?) onSuccess;

  const VerifyCaptchaView(
      {super.key,
      required this.url,
      required this.webviewHeight,
      required this.onSuccess});

  static WebViewController? webViewController;
  static RxBool showLoading = true.obs;
  static RxBool showError = false.obs;

  @override
  Widget build(BuildContext context) {
    webViewController = null;
    Map<String, String> headers = {};
    headers['Accept-Language'] = TranslationService.getLocale().toLanguageTag();
    headers['User-Agent'] = PackageInfoManager.userAgent ?? '';
    webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Theme.of(Get.context!).scaffoldBackgroundColor)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {
            showLoading.value = true;
            showError.value = false;
          },
          onPageFinished: (String url) {
            showLoading.value = false;
          },
          onWebResourceError: (WebResourceError error) {
            showError.value = true;
          },
          onNavigationRequest: (NavigationRequest request) {
            if (request.url.startsWith("inmotion://event")) {
              Uri uri = Uri.parse(request.url);
              String? h = uri.queryParameters['h'];
              webviewHeight.value = double.parse(h ?? '300');
              return NavigationDecision.prevent;
            }

            if (request.url.startsWith("inmotion://env-check")) {
              Uri uri = Uri.parse(request.url);
              String? error = uri.queryParameters['error'];
              String? token = uri.queryParameters['token'];
              String? tokenName = uri.queryParameters['token_name'];

              if (error == '20000' && token != null) {
                onSuccess(token, tokenName);
              }
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(url), headers: headers);

    return Obx(
      () => Container(
          color: Theme.of(context).colorScheme.background,
          height: webviewHeight.value,
          child: Stack(children: [
            ClipRRect(
              borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(15), topRight: Radius.circular(15)),
              child: WebViewWidget(controller: webViewController!),
            ),
            Obx(() => Visibility(
                visible: showLoading.value,
                child: Container(
                  color: Theme.of(context).colorScheme.background,
                  child: Center(
                      child: Loading.loadingWidget(
                          color: Theme.of(context).colorScheme.primary)),
                ))),
          ])),
    );
  }
}
